package cn.spike.rockcc.service.impl;

import cn.spike.rockcc.domain.PayOrder;
import cn.spike.rockcc.dto.Order2Pay;
import cn.spike.rockcc.mapper.PayOrderMapper;
import cn.spike.rockcc.service.IPayOrderService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author spike
 * @since 2023-03-22
 */
@Service
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements IPayOrderService {

    @Override
    public PayOrder selectByOrderNo(String orderNO) {
        Wrapper<PayOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no",orderNO);
        return super.selectOne(wrapper);
    }

    @Override
    @Transactional
    public void createPayOrder(Order2Pay order2Pay) {
        PayOrder payOrder = new PayOrder();
        BeanUtils.copyProperties(order2Pay,payOrder);
        payOrder.setCreateTime(new Date());
        payOrder.setPayStatus(PayOrder.PAY_WAIT);
        super.insert(payOrder);
    }

    @Override
    @Transactional
    public void orderTimeOut(PayOrder payOrder) {
        payOrder.setPayStatus(PayOrder.PAY_CANCEL);
        payOrder.setUpdateTime(new Date());
        super.updateById(payOrder);
    }

    /**
     * 用户取消订单
     * @param orderNo
     */
    @Override
    @Transactional
    public void cancelOrder(String orderNo) {
        Wrapper<PayOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no",orderNo);
        PayOrder payOrder = super.selectOne(wrapper);
        if(payOrder==null) return;
        if(payOrder.getPayStatus().equals(PayOrder.PAY_CANCEL))return;
        payOrder.setPayStatus(PayOrder.PAY_CANCEL);
        payOrder.setUpdateTime(new Date());
        super.insert(payOrder);
    }
}
